package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.enums.FlowTypeEnum;
import com.rongke.enums.PayTypeEnum;
import com.rongke.model.Account;
import com.rongke.model.FlowDetail;
import com.rongke.model.IncomeFlow;
import com.rongke.model.Withdrawals;
import com.rongke.redis.CacheUtil;
import com.rongke.service.*;
import com.rongke.utils.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @version : Ver 1.0
 * @FlowDetailController
 * @交易流水明细Controller
 */
@RestController
@RequestMapping(value = "/api/flowDetail")
@Transactional
@CrossOrigin
public class FlowDetailController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private FlowDetailService flowDetailService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private IncomeFlowService incomeFlowService;
    @Autowired
    private MuserService muserService;
    @Autowired
    private WithdrawalsService withdrawalsService;
    @Autowired
    private CacheUtil cacheUtil;

    /**
     * @param flowDetail
     * @return 返回值JsonResp
     * @添加交易流水明细
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addFlowDetail(@RequestBody FlowDetail flowDetail) {
        log.debug("添加交易流水明细");
        flowDetailService.insert(flowDetail);
        return JsonResp.ok(flowDetail);
    }

    /**
     * @param flowDetail
     * @return 返回值JsonResp
     * @修改交易流水明细
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateFlowDetail(@RequestBody FlowDetail flowDetail) {
        log.debug("修改交易流水明细");
        flowDetailService.updateById(flowDetail);
        return JsonResp.ok(flowDetail);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找交易流水明细
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectFlowDetail(Long id) {
        log.debug("查找交易流水明细");
        FlowDetail flowDetail = flowDetailService.selectById(id);
        return JsonResp.ok(flowDetail);
    }

    /**
     * @param token 令牌
     * @return 返回值JsonResp
     * @金额流水明细（哆币）
     */
    @RequestMapping(value = "/selectDuoBiFlow", method = RequestMethod.GET)
    public JsonResp selectDuoBiFlow(String token) {
        log.debug("金额流水明细（哆币）");
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa(muserService.LOGINSTR);
        }
        String userId = cacheUtil.get(token);
        EntityWrapper<FlowDetail> ew = new EntityWrapper<>();
        ew.eq("muser_id", userId);
        ew.where("(pay_type={0} or flow_type={1})", PayTypeEnum.DUOBI.getType(), FlowTypeEnum.CASHBACKDUOBI.getType());
        ew.orderBy("gmt_datetime", false);
        List<Map> incomes = new ArrayList<>();
        List<FlowDetail> flowDetails = flowDetailService.selectList(ew);
        for (FlowDetail fd : flowDetails) {
            Map flowMap = new HashMap();
            flowMap.put("orderNumber", fd.getOrderNumber());
            flowMap.put("title", fd.getTitle());
            flowMap.put("status", fd.getStatus());
            flowMap.put("money", fd.getMoney());
            flowMap.put("flowType", fd.getFlowType());
            flowMap.put("gmtDatetime", fd.getGmtDatetime());
            incomes.add(flowMap);
        }
        //获取从团队中获益明细
        IncomeFlow incomeFlow = new IncomeFlow();
        incomeFlow.setMuserId(Long.valueOf(userId));
        List<IncomeFlow> incomeFlows = incomeFlowService.selectIncomeFlowList(incomeFlow);
        for (IncomeFlow icf : incomeFlows) {
            Map icfMap = new HashMap();
            icfMap.put("orderNumber", icf.getOrder().getOrderNumber());
            icfMap.put("title", "下线分成+" + icf.getIncome());
            icfMap.put("status", icf.getStatus());
            icfMap.put("money", icf.getIncome());
            icfMap.put("gmtDatetime", icf.getGmtDatetime());
            incomes.add(icfMap);
        }
        //获取哆币提现明细
        EntityWrapper<Withdrawals> ewDrawls = new EntityWrapper<>();
        ewDrawls.eq("muser_id", userId);
        List<Withdrawals> withdrawals = withdrawalsService.selectList(ewDrawls);
        for (Withdrawals wd : withdrawals) {
            Map ddMap = new HashMap();
            ddMap.put("alipayNo", wd.getAlipayNo());
            ddMap.put("title", wd.getTitle());
            ddMap.put("money", wd.getMoney());
            ddMap.put("status", wd.getStatus());
            ddMap.put("gmtDatetime", wd.getGmtDatetime());
            incomes.add(ddMap);
        }
        EntityWrapper<Account> ewAcc = new EntityWrapper<>();
        ewAcc.eq("muser_id", userId);
        Account accounts = accountService.selectOne(ewAcc);
        Map map = new HashMap();
        map.put("flowDetails", incomes);
        map.put("rebateDuobi", accounts.getRebateDuobi());
        return JsonResp.ok(map);
    }

    /**
     * 返现哆币雅币明细
     * @param token
     * @return
     */
    @RequestMapping(value = "/getReturnFlow", method = RequestMethod.GET)
    public JsonResp getReturnFlow(String token, Page page) {
        log.debug("返现哆币雅币明细");
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa(muserService.LOGINSTR);
        }
        String userId = cacheUtil.get(token);
        EntityWrapper<FlowDetail> ew = new EntityWrapper<>();
        ew.eq("muser_id", userId);
        ew.in("flow_type", Arrays.asList("5", "6"));
        ew.orderBy("gmt_datetime", false);
        Page<FlowDetail> fdPage = flowDetailService.selectPage(page, ew);
        return JsonResp.ok(fdPage);
    }


    /**
     * @param token 令牌
     * @return 返回值JsonResp
     * @金额流水明细（提现记录）
     */
    @RequestMapping(value = "/selectTiXianFlow", method = RequestMethod.GET)
    public JsonResp selectTiXianFlow(String token) {
        log.debug("金额流水明细（提现记录）");
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa(muserService.LOGINSTR);
        }
        String userId = cacheUtil.get(token);
        EntityWrapper<FlowDetail> ew = new EntityWrapper<>();
        ew.eq("muser_id", userId);
        ew.eq("flow_type", FlowTypeEnum.WITHDRAWALS.getType());
        ew.orderBy("gmt_datetime", false);
        List<FlowDetail> flowDetails = flowDetailService.selectList(ew);
        return JsonResp.ok(flowDetails);
    }

    /**
     * @param token 令牌
     * @return 返回值JsonResp
     * @金额流水明细（雅币明细）
     */
    @RequestMapping(value = "/selectYabiFlow", method = RequestMethod.GET)
    public JsonResp selectYabiFlow(String token) {
        log.debug("金额流水明细（雅币明细）");
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa(muserService.LOGINSTR);
        }
        String userId = cacheUtil.get(token);
        EntityWrapper<FlowDetail> ew = new EntityWrapper<>();
        ew.eq("muser_id", userId);
        //2 "转让",6 "购买雅币返现",8 "雅币退款", 11 "体验推荐审核通过奖励雅币"
        ew.where("(pay_type={0} or flow_type in (2,6,8,11))", PayTypeEnum.YABI.getType());
        ew.orderBy("gmt_datetime", false);
        List<FlowDetail> flowDetails = flowDetailService.selectList(ew);
        EntityWrapper<Account> ewAcc = new EntityWrapper<>();
        ewAcc.eq("muser_id", userId);
        Account accounts = accountService.selectOne(ewAcc);
        Map map = new HashMap();
        map.put("flowDetails", flowDetails);
        map.put("rebateYabi", accounts.getRebateYabi());
        return JsonResp.ok(map);
    }


    /**
     * @param token 令牌
     * @return 返回值JsonResp
     * @金额流水明细（雅币转账明细）
     */
    @RequestMapping(value = "/selectTransferFlow", method = RequestMethod.GET)
    public JsonResp selectTransferFlow(String token) {
        log.debug("金额流水明细（雅币转账明细）");
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa(muserService.LOGINSTR);
        }
        String userId = cacheUtil.get(token);
        EntityWrapper<FlowDetail> ew = new EntityWrapper<>();
        ew.eq("muser_id", userId);
        ew.eq("flow_type", FlowTypeEnum.TRANSFER.getType());
        ew.orderBy("gmt_datetime", false);
        List<FlowDetail> flowDetails = flowDetailService.selectList(ew);
        return JsonResp.ok(flowDetails);
    }


    /**
     *
     * @param muserId  会员id
     * @param type  类型 1不可用哆币2不可用雅币3返现哆币4返现雅币5消费总额
     * @return
     */
    @RequestMapping(value = "/selectFlowList",method = RequestMethod.GET)
    public JsonResp selectFlowList(Long muserId,Integer type,Page page,String orderNumber){
        EntityWrapper<FlowDetail> ew=new EntityWrapper<>();
        ew.eq("muser_id",muserId);
        if(type==1){
            ew.eq("status",5);
            ew.eq("flow_type",FlowTypeEnum.CASHBACKDUOBI.getType());
        }else if(type==2){
            ew.eq("status",5);
            ew.eq("flow_type",FlowTypeEnum.CASHBACKYABI.getType());
        }else if(type==3){
            ew.eq("status",4);
            ew.eq("flow_type",FlowTypeEnum.CASHBACKDUOBI.getType());
        }else if(type==4){
            ew.eq("status",4);
            ew.eq("flow_type",FlowTypeEnum.CASHBACKYABI.getType());
        }else {
            String payType="";
            for (PayTypeEnum payTypeEnum : PayTypeEnum.values()) {
                payType+=payTypeEnum.getType()+"";
            }
            if(!"".equals(payType)){
                payType=payType.substring(0,payType.length()-1);
            }
            ew.where("find_in_set(pay_type,{0}) >0",payType);
        }

        if(StringUtil.isNotEmpty(orderNumber)){
            ew.like("order_number",orderNumber);
        }
        ew.orderBy("gmt_datetime",false);
        Page<FlowDetail> flowDetailList=flowDetailService.selectPage(page,ew);
        return JsonResp.ok(flowDetailList);
    }

    /**
     *  查询雅币转账记录
     * @param data  查询条件
     * @return
     */
    @RequestMapping(value = "/selectTransferList",method = RequestMethod.GET)
    public JsonResp selectTransferList(String data,Page page){
         Map map=new HashMap();
        map.put("startIndex",(page.getCurrent()-1)*page.getCurrent());
        map.put("size",page.getSize());
        map.put("flowType",FlowTypeEnum.TRANSFER.getType());
         if(StringUtil.isNotEmpty(data)){
             if(data.matches("^[0-9]*$")){
                 map.put("phone",data);
             }else{
                 map.put("userName",data);
             }
         }
        List<Map> maps=flowDetailService.selectTransferList(map);
        Integer size=flowDetailService.selectTransferListSize(map);
        page.setRecords(maps);
        page.setTotal(size);
        return JsonResp.ok(page);
    }


    /**
     *  查询某会员转账记录列表
     * @param userId  会员id
     * @return
     */
    @RequestMapping(value = "/selectUserTransferList",method = RequestMethod.GET)
    public JsonResp selectUserTransferList(Long userId,Page page){
        Map map=new HashMap();
        map.put("muserId",userId);
        map.put("startIndex",(page.getCurrent()-1)*page.getCurrent());
        map.put("size",page.getSize());
        List<Map> maps=flowDetailService.selectTransferListByUserId(map);
        Integer size=flowDetailService.selectTransferListByUserIdSize(map);
        page.setRecords(maps);
        page.setTotal(size);
        return JsonResp.ok(page);
    }


}
